package org.jeecg.modules.article.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Before;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.MQConstant;
import org.jeecg.common.mq.config.ActiveMQBeanConfig;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.constant.ConsumerConstant;
import org.jeecg.constant.ElasticSearchConstant;
import org.jeecg.constant.RedisConstant;
import org.jeecg.modules.article.entity.Article;
import org.jeecg.modules.article.service.IArticleService;
import org.jeecg.modules.article.vo.RotationVO;
import org.jeecg.modules.article.vo.ToGetTopicArticleDetailVO;
import org.jeecg.modules.comment.entity.PhilComment;
import org.jeecg.modules.comment.service.IPhilCommentService;
import org.jeecg.modules.es.service.ElasticSearchService;
import org.jeecg.modules.wechat.service.IWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 文章
 * @Author: jeecg-boot
 * @Date:   2020-10-14
 * @Version: V1.0
 */
@Api(tags="文章")
@RestController
@RequestMapping("/phil/article")
@Slf4j
public class ArticleController extends JeecgController<Article, IArticleService> {
	@Autowired
	private IArticleService articleService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private ElasticSearchService elasticSearchService;
	@Autowired
	private ActiveMQBeanConfig activeMQBeanConfig;
	@Autowired
	private JmsMessagingTemplate jmsMessagingTemplate;
	@Autowired
	private IPhilCommentService commentService;
	@Autowired
	private IWxUserService wxUserService;
	/**
	 * 分页列表查询
	 *
	 * @param article
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "文章-分页列表查询")
	@ApiOperation(value="文章-分页列表查询", notes="文章-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Article article,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Article> queryWrapper = QueryGenerator.initQueryWrapper(article, req.getParameterMap());
		queryWrapper.orderByDesc("create_time");
		Page<Article> page = new Page<Article>(pageNo, pageSize);
		IPage<Article> pageList = articleService.page(page, queryWrapper);

		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param article
	 * @return
	 */
	@AutoLog(value = "文章-添加")
	@ApiOperation(value="文章-添加", notes="文章-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody Article article) {
		// 获取雪花id，并设置文章id
		Snowflake snowflake = IdUtil.createSnowflake(1,1);
		String id = snowflake.nextIdStr();
		article.setId(id);
		articleService.save(article);
		// 订阅服务通知，同时更新es，用广播
//		jmsMessagingTemplate.convertAndSend(activeMQBeanConfig.topicColumnPublish(),article);
		Map<String, Object> map = new HashMap<>();
		map.put(MQConstant.OPERATION,ConsumerConstant.PHIL_PUBLISH_ARTICLE);
		map.put(MQConstant.INFO, JSON.toJSONString(article));
		jmsMessagingTemplate.convertAndSend(activeMQBeanConfig.queueTopicRedis(),map);
		// 更新轮播图
		jmsMessagingTemplate.convertAndSend(activeMQBeanConfig.queueUpdateRedis(), ConsumerConstant.ROTATION);
		return Result.ok("添加成功！");
	}


	/**
	 *  编辑
	 *
	 * @param article
	 * @return
	 */
	@AutoLog(value = "文章-编辑")
	@ApiOperation(value="文章-编辑", notes="文章-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody Article article) {
		articleService.updateById(article);
		// 更新轮播图
		jmsMessagingTemplate.convertAndSend(activeMQBeanConfig.queueUpdateRedis(), ConsumerConstant.ROTATION);
		// 获取id 更新es
		String id = article.getId();
		elasticSearchService.updateDocument(ElasticSearchConstant.PHIL_ARTICLE,id,article,"10s");
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "文章-通过id删除")
	@ApiOperation(value="文章-通过id删除", notes="文章-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		articleService.removeById(id);
		// 更新轮播图
		redisUtil.del(RedisConstant.TOPROTATION);
		// 获取id 删除es文档
		elasticSearchService.deleteDocument(ElasticSearchConstant.PHIL_ARTICLE,id,"10s");
		// 删除该文章下的评论
		commentService.
				remove(new LambdaQueryWrapper<PhilComment>()
				.eq(PhilComment::getArticleId,id));
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "文章-批量删除")
	@ApiOperation(value="文章-批量删除", notes="文章-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> list = Arrays.asList(ids.split(","));
		this.articleService.removeByIds(list);
		// 更新轮播图
		jmsMessagingTemplate.convertAndSend(activeMQBeanConfig.queueUpdateRedis(), ConsumerConstant.ROTATION);
		list.forEach(id->{
			elasticSearchService.deleteDocument(ElasticSearchConstant.PHIL_ARTICLE,id,"10s");
			// 删除该文章下的评论
			commentService.
					remove(new LambdaQueryWrapper<PhilComment>()
							.eq(PhilComment::getArticleId,id));
		});
		return Result.OK("批量删除成功!");
	}


	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "文章-通过id查询")
	@ApiOperation(value="文章-通过id查询", notes="文章-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id,@RequestParam(name = "openId",required = false) String openId) {
		Article article = articleService.getById(id);
		if(article==null) {
			return Result.error("未找到对应数据");
		}
		//判断用户是否加分
		if (StrUtil.isNotBlank(openId)) {
			long res = redisUtil.sSet(RedisConstant.READING + id, openId);
			if (res==1){
				// 说明是今天第一次阅读本文章，加分
				wxUserService.updateUserScore(openId,true,1);
			}
		}
		articleService.updateReadingNum(id);
		return Result.OK(article);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param article
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Article article) {
        return super.exportXls(request, article, Article.class, "文章");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Article.class);
    }

    /**
	 *更新阅读数量
	 *
	 * @param  articleId
	 *
	 * */
    @AutoLog(value = "文章-更新阅读量")
	@ApiOperation(value="文章-更新阅读量", notes="文章-更新阅读量")
    @RequestMapping(value = "/updateReadingNum",method = RequestMethod.POST)
    public Result<?> updateReadingNum(@ApiParam(value ="文章id",required = true)String articleId){

    	return Result.OK(articleService.updateReadingNum(articleId)) ;
	}



	@AutoLog(value = "首页推荐")
	 @ApiOperation(value = "文章-首页推荐",notes = "文章-首页推荐")
	 @RequestMapping(value = "/queryListByHomePageIsTrue",method = RequestMethod.GET)
	 public Result<?> queryListByHomePageIsTrue(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												@RequestParam(name="pageSize", defaultValue="10") Integer pageSize){

		Page<Article> page = new Page<Article>(pageNo, pageSize);
		Page<Article> pageList = articleService.queryListByHomePageIsTrue(page);

    	return Result.OK(pageList);
	}


	/**
	 * TODO: 获取轮播图
	 *
	 *
	 * @author ZhangHaoyu
	 * @return org.jeecg.common.api.vo.Result<?>
	 */
	 @AutoLog(value = "app获取轮播图")
	 @ApiOperation(value = "app获取轮播图",notes = "app获取轮播图")
	 @RequestMapping(value = "/getTopRotation",method = RequestMethod.GET)
	 public Result<?> getTopRotation(){
		 List<RotationVO> topRotation = articleService.getTopRotation(0);
		 return Result.OK(topRotation);
	 }

	/**
	 * TODO: app获取新推文章的信息，用于我的订阅界面
	 *
	 *
	 * @author ZhangHaoyu
	 * @return org.jeecg.common.api.vo.Result<?>
	 */
	@AutoLog(value = "app获取新推文章的信息")
	@ApiOperation(value = "app获取新推文章的信息",notes = "app获取新推文章的信息")
	@RequestMapping(value = "/getArticleByList",method = RequestMethod.POST)
	public Result<?> getArticleInfoByList(@RequestBody ToGetTopicArticleDetailVO toGetTopicArticleDetailVO){
		String openId = toGetTopicArticleDetailVO.getOpenId();
		String columnId = toGetTopicArticleDetailVO.getColumnId();

		// 从redis中获取栏目id并置为空
		HashMap<String, Object> map= (HashMap<String, Object>) redisUtil.get(RedisConstant.ARTICLE_PUBLISH + columnId);
		Object o = map.get(openId);
		if (o==null){
			return Result.OK();
		}
		Set<String> set = (Set<String>)o;
		List<Article> list = articleService.listByIds(set);

		// 异步清空该栏目下该用户的推送文章
		Map<String, String> info = new HashMap<>(2);
		info.put("openId",openId);
		info.put("columnId",columnId);
		Map<String, Object> map2 = new HashMap<>(2);
		map2.put(MQConstant.OPERATION,ConsumerConstant.PHIL_CLEAR_COLUMN_PUBLISH_ARTICLE);
		map2.put(MQConstant.INFO, JSON.toJSONString(info));
		jmsMessagingTemplate.convertAndSend(activeMQBeanConfig.queueTopicRedis(),map2);
		return Result.OK(list);
	}


	/**
	 * TODO: app根据栏目获取文章有排序
	 *
	 *
	 * @author ZhangHaoyu
	 * @return org.jeecg.common.api.vo.Result<?>
	 */
	@AutoLog(value = "app根据栏目获取文章有排序")
	@ApiOperation(value = "app根据栏目获取文章有排序",notes = "app根据栏目获取文章有排序")
	@RequestMapping(value = "/getColumnTopArticle",method = RequestMethod.GET)
	public Result<?> getColumnTopArticle(@RequestParam(value = "columnName") String columnName,
										 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
										 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){
		Page<Article> page = new Page<Article>(pageNo, pageSize);
		Page<Article> pageList = articleService.getSortArticleByColumn(page,columnName);

		return Result.OK(pageList);
	}
}
